from storageEngine import IStorageEngine
import sqlite3
class SqliteStorage(IStorageEngine):
    class ISqliteDao(IStorageEngine.IDao):
        def createSql(self, **kwargs):
            pass
        def dropSql(self, **kwargs):
            pass
        def insertSql(self, **kwargs):
            pass
        def deleteSql(self, **kwargs):
            pass
        def updateSql(self, **kwargs):
            pass
        def querySql(self, **kwargs):
            pass
        def toPojo(self, obj, **kwargs):
            pass


    def __init__(self, url):
        self.__url = url
        self.__connection = sqlite3.connect(self.__url)

    def close(self):
        self.__connection.close()

    def __execute(self, sql, isNeedEffectRows = True):
        print("StorageEngine sql:" + sql)
        ret = 0
        if isNeedEffectRows == True:
            cursor = self.__connection.cursor()
            cursor.execute(sql)
            ret = cursor.rowcount
            cursor.close()
        else:
            ret = self.__connection.execute(sql)
        self.__connection.commit()
        return ret

    def __executeQuery(self, selectSql):
        print("StorageEngine [select] sql:" + selectSql)
        cursor = self.__connection.cursor()
        cursor.execute(selectSql)
        return cursor.fetchall()

        

    def create(self, sqlObj, **kwargs):
        if isinstance(sqlObj, SqliteStorage.ISqliteDao):
            return self.__execute(sqlObj.createSql(**kwargs), False)
        else:
            print("Error, type error, need ISqliteDao")

        
    def drop(self, sqlObj, **kwargs):
        if isinstance(sqlObj, SqliteStorage.ISqliteDao):
            return self.__execute(sqlObj.dropSql(**kwargs), False)
        else:
            print("Error, type error, need ISqliteDao")

    def insert(self, sqlObj, **kwargs):
        if isinstance(sqlObj, SqliteStorage.ISqliteDao):
            return self.__execute(sqlObj.insertSql(**kwargs))
        else:
            print("Error, type error, need ISqliteDao")

    def delete(self, sqlObj, **kwargs):
        if isinstance(sqlObj, SqliteStorage.ISqliteDao):
            return self.__execute(sqlObj.deleteSql(**kwargs))
        else:
            print("Error, type error, need ISqliteDao")
        
    def update(self, sqlObj, **kwargs):
        if isinstance(sqlObj, SqliteStorage.ISqliteDao):
            return self.__execute(sqlObj.updateSql(**kwargs))
        else:
            print("Error, type error, need ISqliteDao")
    def query(self, sqlObj, **kwargs):
        if isinstance(sqlObj, SqliteStorage.ISqliteDao):
            sql = sqlObj.querySql(**kwargs)
            rows = self.__executeQuery(sql)
            return sqlObj.toPojo(rows, **kwargs)
        else:
            print("Error, type error, need ISqliteDao")

#end class
